from langchain_zhipu import ChatZhipuAI, ZhipuAIEmbeddings
from langchain_core.output_parsers import StrOutputParser
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.prompts import ChatPromptTemplate

from langchain.chains.combine_documents import create_stuff_documents_chain

from langchain_core.documents import Document
from langchain_community.document_loaders import WebBaseLoader
from langchain.chains import create_retrieval_chain

from langchain_community.document_loaders import TextLoader



llm = ChatZhipuAI(api_key="d3708ee404327e207b2f003775e06908.X3dgRCxbkyDfEIbh"
                  , model="glm-4")
embeddings = ZhipuAIEmbeddings(api_key="d3708ee404327e207b2f003775e06908.X3dgRCxbkyDfEIbh")

loader = WebBaseLoader("https://docs.smith.langchain.com/user_guide")

docs = loader.load()
# loader = TextLoader("index.md")
# localText = loader.load()

text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
print(documents)
vector = FAISS.from_documents(documents, embeddings)

prompt = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context:

<context>
{context}
</context>

Question: {input}""")
document_chain = create_stuff_documents_chain(llm, prompt)
# answer = document_chain.invoke({
#     "input": "how can langsmith help with testing?",
#     "context": [Document(page_content="langsmith can let you visualize test results")]
# })
# print(answer)

retriever = vector.as_retriever()
retrieval_chain = create_retrieval_chain(retriever, document_chain)
response = retrieval_chain.invoke({"input": "how can langsmith help with testing?"})
print(response["answer"])
